package dk.dtu.android.transport.db;

import android.content.ContentValues;
import android.database.Cursor;

public class KeyValueTable extends BaseDbAdapter {

	protected static String TABLE_NAME = "KEY_VALUE";
	
	protected static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY, key TEXT, value TEXT)";

	
	public KeyValueTable(String key, String value) {
	}
	
	/* Static methods */
	
	private static void insert(String key, String value)
	{
		ContentValues args = new ContentValues();
		args.put("key", key);
		args.put("value", value);
		db.insert(TABLE_NAME, null, args);
	}
	
	private static void update(String key, String value)
	{
		ContentValues args = new ContentValues();
		args.put("value", value);
		db.update(TABLE_NAME, args, "key = ?", new String[] {key});
	}
	
	public static void setValue(String key, String value)
	{
		String currentValue = getValue(key);
		if (currentValue == null)
		{
			insert(key, value);
		}
		else 
		{
			update(key, value);
		}
	}
	
	public static void deleteValue(String key)
	{
		db.delete(TABLE_NAME, "key = ?", new String[] {key});
	}
	
	public static String getValue(String key)
	{
		return getValue(key, null);
	}
	
	public static String getValue(String key, String defaultValue)
	{
		Cursor cursor = db.query(TABLE_NAME, new String[] {"value"}, "key = ?", new String[] {key}, null, null, null);
		String value = defaultValue;
		if (cursor.moveToFirst())
		{
			do {
				value = cursor.getString(0);
			} while (cursor.moveToNext());
		}
		return value;
	}
}
